//
//  SelectMapPointView2.swift
//  JiaoZiTaxi
//
//  Created by shanzachattha8@gmail.comArmy1122@ on 2025/5/24.
//

import SwiftUI
import MapKit

struct SelectMapPointManager: View {
    @Environment(\.dismiss) var dismiss
    
    @State var addressList: [AddressModel] = []
    @StateObject private var addressManager = MyAddressNetManager()
    
    @State var selectCoordinate: CLLocationCoordinate2D = CarOrder.shared.startPos!
    
    @ObservedObject var carOrder = CarOrder.shared
    
    var action : (AddressModel)->Void
    
    @State var lastLocation: CLLocationCoordinate2D = ViewModel.shared.lastLocation
    
    var body: some View {
        GeometryReader(content: { geometry in
            
            NavigationView {
                ZStack {
                    VStack{
                        SelectMapPointView(region: MKCoordinateRegion(
                            center: CLLocationCoordinate2D(latitude:lastLocation.latitude, longitude: lastLocation.longitude),
                            span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
                        ), selectCoordinate:$selectCoordinate, selectType: "end") { coordinate in
                            self.lastLocation = coordinate
                            Api.googleNearbyPlaces(openId: ViewModel.shared.passenger.openId, latitude:"\(coordinate.latitude)" , longitude: "\(coordinate.longitude)") { r in
                                    switch r {
                                    case .success(let addresses):
                                        print("查询到的地址\(addresses)")
                                        DispatchQueue.main.async {
                                            self.addressList = addresses
                                        }
                                    case .failure(let addresses):
                                        print("\(addresses)")
                                    }
                                }
                        }
                        
                    }
                    .frame(width: geometry.size.width)
                   
                    VStack{
                        Spacer()
                        HStack{
                            Spacer()
                            Button {
                                selectCoordinate = CarOrder.shared.startPos!
                            } label: {
                                Image("首页_定位")
                                    .resizable()
                                    .frame(width: 40, height: 40)
                            }
                            
                        }
                    
                        List{
                            ForEach(addressList, id: \.self) { address in
                                Button {
                                    
//                                    let lat = address.latitude
//                                    let lon = address.longitude
//                                    let pos = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
//                                   
//                                    ViewModel.shared.endLocation = pos
//                                    carOrder.endPos = pos
//                                    carOrder.endLabel = "\(address.name ?? "")"
//                                    MapConfig.shared.startOrEndChanged = true
//                                    
                                        dismiss()
                                        self.action(address)
                                    
                                    
                                } label: {
                                    createPublicCell(address: address)
                                }
                            }
                        }
                        .frame(width: geometry.size.width,height: geometry.size.height/2-30)
                        .background(.white)
                        .listStyle(.plain)           // 移除默认样式
                        .padding(.horizontal, 0)     // 移除水平边距
                        .background(Color.clear)     // 确保背景透明
                        
                    }
                    .frame(width: geometry.size.width,height: geometry.size.height)
                    
                }
                .background(Color.backgroundColor())
            }.navigationBarBackButtonHidden(true) // 隐藏默认返回按钮
                    .navigationBarItems(leading: backButton) // 添加自定义返回按钮
                    .navigationTitle("地图选点")
            
        })
        //公共cell
       
      
    }
    
    func createPublicCell(address : AddressModel) -> some View{
        HStack{
            Image("地图选点_设置")
            Text("\(address.longname!)").font(.system(size: 14))
            Spacer()
            Text("\(lastLocation.distance(to: CLLocationCoordinate2D(latitude: (address.latitude)!, longitude: (address.longitude)!)))")
            
            
        }.frame(maxWidth: .infinity, alignment: .leading)
            .padding(.vertical,10)
    }
    
    
    var backButton: some View {
        Button(action: {
            dismiss()
        }) {
            HStack {
                Image(systemName: "chevron.backward")
                    .foregroundColor(.black)
            }
        }
    }
}



//#Preview {
//    SelectMapPointManager()
//}

